package com.zaoqi.controller;

import com.zaoqi.anno.Log;
import com.zaoqi.pojo.Device;
import com.zaoqi.pojo.Result;
import com.zaoqi.repository.DeviceRepository;
import com.zaoqi.service.SensorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Log
@RestController
@RequestMapping("/api/sensor")
public class SensorController {
    @Autowired
    private DeviceRepository deviceRepository;
    @Autowired
    private SensorService sensorService;

    @PostMapping("/data")
    public Result getSensorData(@RequestBody Map<String, List<String>> request) {
        try {
            // 获取 ids 参数
            List<String> ids = request.get("ids");
            if (ids == null || ids.isEmpty()) {
                return Result.error("参数 'ids' 不能为空");
            }
            // 查询数据库中的设备信息
            List<Device> devices = sensorService.getDevicesBySerialNumbers(ids);
            if (devices.isEmpty()) {
                return Result.error("未找到匹配的设备信息");
            }
            // 调用外部 API 获取数据
            List<Object> sensorData = sensorService.fetchSensorDataFromApi(ids);
            // 返回设备信息和外部数据
            return Result.success(Map.of(
                    "devices", devices,
                    "sensorData", sensorData
            ));
        } catch (Exception e) {
            return Result.error("获取传感器数据失败：" + e.getMessage());
        }
    }
    @GetMapping("/data")
    public List<DeviceInfoDTO> getAllDevices() {
        // 查询所有设备信息
        List<Device> devices = deviceRepository.findAll();
        // 转换为 DeviceInfoDTO，拼接 name 和 category 字符串
        return devices.stream()
                .map(device -> new DeviceInfoDTO(
                        device.getName() + device.getCategory(), // 拼接 Name 和 Category
                        device.getUnit()
                ))
                .collect(Collectors.toList());
    }
    // DTO (数据传输对象)
    public static class DeviceInfoDTO {
        private String nameAndCategory; // 拼接的 name 和 category
        private String unit; // 数据采集单位

        public DeviceInfoDTO(String nameAndCategory, String unit) {
            this.nameAndCategory = nameAndCategory;
            this.unit = unit;
        }
        public String getNameAndCategory() {
            return nameAndCategory;
        }
        public void setNameAndCategory(String nameAndCategory) {
            this.nameAndCategory = nameAndCategory;
        }
        public String getUnit() {
            return unit;
        }
        public void setUnit(String unit) {
            this.unit = unit;
        }
    }
}
